import React, {FC, useCallback, useContext, useState} from 'react';
import "./index.less";
import default_art_cover from "@/assets/default_art_cover.png";
import {Breadcrumb, Button, Form, Image, message, Space} from "antd";
import HxCyCard from "@/components/HxCyCard";
import JournalInfoMeta from "@/pages/JournalPage/JournalDetail/commons/JournalInfoMeta";
import MallJournalsGuess from "@/pages/MallPage/MallProductDetail/MallJournalsGuess";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {Link, useParams} from "@@/exports";
import {useCountDown, useRequest} from "ahooks";
import * as API from "@/services";
import {correspVal, getArticleLocationStr} from "@/utils/biz";
import {KfBackendEnumPicker, KfModal, KfRadioGroup, useBackendEnum} from "kf-web-library";
import * as numeral from "numeral";
import {MallOrderConfirmInfo} from "@/pages/MallPage/MallOrder";
import {OrderConfirmInfo} from "@/pages/MallPage/MallOrder/MallOrderConfirmInfo";
import {MallOrderContext} from "@/pages/MallPage/MallOrder/MallOrderContext";

import useAuthedCheck from "@/components/hooks/UseAuthedCheck";
import HxMallJournalPeriodPicker, {MallJournalPeriodPickerValueType} from "@/components/HxMallJournalPeriodPicker";
import {existFrontJournalPeriod} from "@/services";
import {FormattedMessage} from "umi";
import HealthScienceAd from "@/pages/MinePage/HealthScienceAd";

interface MallProductDetailProps {
}


const postJournals = [
  {name: "Signal Transduetion and Targeted Therapy (信号转导与靶向治疗)", code: "62-626"},
  {name: "华西医学", code: "62-70"},
  {name: "中国循证医学杂志", code: "62-245"},
  {name: "中国胸心血管外科临床杂志", code: "62-126"},
  {name: "中国修复重建外科杂志", code: "62-80"},
  {name: "中国普外基础与临床杂志", code: "62-7"},
  {name: "中华眼底病杂志", code: "62-73"},
  {name: "中国呼吸与危重监护杂志", code: "62-246"},
  {name: "生物医学工程学杂志", code: "62-65"},
  {name: "癫痫杂志", code: "62-604"},
  {name: "Precision Clinical Medicine (精准临床医学)", code: "62-633"},
  {name: "ACTAEPILEPTOLOGICA (癫痫学报)", code: "62-634"},
]


const MallProductDetail: FC<MallProductDetailProps> = (props) => {
  const {isZhCN, siteInfo} = useContext(HxConfigContext)
  const {journalId} = useParams();
  const [form] = Form.useForm();
  const authedCheck = useAuthedCheck();
  const [orderConfirmInfo, setOrderConfirmInfo] = useState<OrderConfirmInfo | undefined>(undefined);    //订单确认信息

  const {enumDict, enumTypeDict, getBackendEnum} = useBackendEnum();
  const journalReq = useRequest(() => API.queryFrontJournal(journalId!), {
    ready: !!journalId,
    refreshDeps: [journalId],
  });
  const periodExistReq = useRequest(() => API.existFrontJournalPeriod(journalId!), {
    ready: !!journalId,
    refreshDeps: [journalId],
  });
  const plansReq = useRequest(() => API.queryFrontJournalSubscribePlans({journalId}), {
    ready: !!journalId,
    refreshDeps: [journalId],
    onSuccess: (resp) => {
      if (resp.flag && resp.data?.length > 0) {
        form.setFieldsValue({
          subscribePlanId: resp.data[0].id,
          periods: [],
          carrierType: "ELECTRONIC_JOURNAL",
          timeType: "FUTURE",
        });
      }
    }
  });

  const onPaymentSuccess = useCallback(() => {
    setOrderConfirmInfo(undefined);   //关闭弹窗
    message.success("订单支付成功!");
    //todo 支付成功的跳转逻辑待完成
  }, []);

  //SubscribeDisplayType
  const plans = plansReq.data?.data || [];
  const journal = journalReq.data?.data;
  const periodExist = periodExistReq.data?.data;

  return (
    <div className={"mall-product-detail-container-wrapper"}>
      <Breadcrumb
        className={"mall-product-detail-breadcrumd"}
        items={[
          {title: (<Link to={`/`}><FormattedMessage id="menu.home"/></Link>)},
          {title: (<Link to={`/mall`}><FormattedMessage id="menu.mall"/></Link>)},
          {title: correspVal(isZhCN, journal?.journalNameCn, journal?.journalNameEn)}
        ]}
      />
      <div className={"mall-product-detail-container"}>
        <div className={"mall-product-detail-left"}>
          <div className={"mall-product-detail-info"}>
            <div className={"mall-product-detail-info-top"}>
              <div className={"mall-product-detail-info-cover"}>
                <Image src={journal?.journalCoverPathUrl} fallback={default_art_cover} preview={false}/>
              </div>
              <div className={"mall-product-detail-info-body"}>
                <div className={"mall-product-detail-info-header"}>
                  <div className={"mall-product-detail-info-title"}>
                    {correspVal(isZhCN, journal?.journalNameCn, journal?.journalNameEn)}
                  </div>
                  <div className={"mall-product-detail-info-meta"}>
                    {!!journal && (
                      <Form
                        form={form}
                        colon={false}
                        className={`mall-subscribe-form mall-subscribe-form-${isZhCN ? "cn" : "en"}`}
                        onFinish={(values) => {
                          authedCheck(() => {
                            const displayType = values.carrierType;
                            const timeType = values.timeType;
                            const planId = values.subscribePlanId;
                            const periods: MallJournalPeriodPickerValueType[] = values.periods;
                            const plan = plans?.find(item => item.id === planId);

                            if (!displayType) {
                              message.error("订阅载体不能为空!")
                              return;
                            }
                            if (timeType === "FUTURE" && !plan) {
                              message.error("订阅选择(套餐)必须选取!")
                              return;
                            }
                            if (timeType === "HISTORICAL" && periods?.length === 0) {
                              message.error("订阅选择(往期期数)至少选取1项.")
                              return;
                            }

                            setOrderConfirmInfo({
                              displayType: values.carrierType,
                              timeType: values.timeType,
                              periods: periods,
                              plan: plan,
                              journal: journal!,
                            })
                          })
                        }}
                      >
                        <Form.Item noStyle shouldUpdate={(prev, curr) => (
                          prev.subscribePlanId != curr.subscribePlanId ||
                          prev.timeType != curr.timeType ||
                          prev.periods?.length != curr.periods?.length
                        )}>
                          {({getFieldValue}) => {
                            const timeType = getFieldValue("timeType");
                            const planId = getFieldValue("subscribePlanId");
                            const periods = getFieldValue("periods") || [];

                            let totalAmount: number | undefined = undefined;
                            if (timeType === "FUTURE") {
                              const plan = plans?.find(item => item.id === planId);
                              if (plan) {
                                totalAmount = plan?.totalPrice;
                              }
                            } else if (timeType === "HISTORICAL") {
                              if (periods.length > 0) {
                                totalAmount = (journal.regularPrice || 0) * periods.length;
                              }
                            }
                            return (
                              <Form.Item
                                label={<FormattedMessage id="mall.SubscriptionPrice"/>}
                                help=""
                                hasFeedback={false}
                                rules={[{required: false}]}
                              >
                                <Space size={20}>
                              <span className={"mp-order-price"}>
                                {
                                  totalAmount != undefined ? (
                                      <> ￥{numeral(totalAmount / 100).format('0.00')}</>
                                    ) :
                                    (
                                      <span className={"mp-order-incomplete-tip"}> <FormattedMessage id="mall.subscription-select-confirm"/> </span>
                                    )
                                }
                              </span>

                                  {/*{
                                plan?.unitPrice >0 && (
                                  <Space size={16}>
                                    <span className={"mp-order-unit-price"}>单价:￥{numeral(plan?.unitPrice/100).format('0.00')}</span>
                                    <span className={"mp-order-year-price"}>年价:￥300.00</span>
                                  </Space>
                                )
                              }*/}
                                </Space>
                              </Form.Item>
                            )
                          }}
                        </Form.Item>

                        <Form.Item noStyle shouldUpdate={(prev, curr) => prev.timeType != curr.timeType}>
                          {({getFieldValue, setFieldValue}) => {
                            const timeType = getFieldValue("timeType");
                            if (timeType === "HISTORICAL") {
                              //往期只有电子版
                              setFieldValue("carrierType", "ELECTRONIC_JOURNAL")
                            }
                            return (
                              <Form.Item
                                label={<FormattedMessage id="mall.SubscriptionCarrier"/>}
                                help=""
                                name={"carrierType"}
                                hasFeedback={false}
                                rules={[{required: false}]}
                              >
                                <KfBackendEnumPicker.RadioGroup
                                  optionType="button"
                                  enumType={"SubscribeDisplayType"}
                                  disabled={timeType === "HISTORICAL" ? ["PRINT_JOURNAL"] : []}
                                />
                              </Form.Item>
                            )
                          }}
                        </Form.Item>
                        <Form.Item
                          label={<FormattedMessage id="mall.SubscriptionPeriod"/>}
                          help=""
                          name={"timeType"}
                          hasFeedback={false}
                          rules={[{required: false}]}
                        >
                          <KfBackendEnumPicker.RadioGroup
                            optionType="button"
                            enumType={"SubscribeTimeType"}
                            disabled={periodExist ? [] : ["HISTORICAL"]}  //不存在刊期数据就disable掉"往期"
                          />
                        </Form.Item>

                        <Form.Item noStyle shouldUpdate={(prev, curr) => prev.timeType != curr.timeType}>
                          {({getFieldValue}) => {
                            const timeType = getFieldValue("timeType");
                            if (timeType === "FUTURE") {
                              return (
                                <Form.Item
                                  label={<FormattedMessage id="mall.SubscriptionSelect"/>}
                                  help={""}
                                  name={"subscribePlanId"}
                                  hasFeedback={false}
                                  rules={[{required: false}]}
                                >
                                  <KfRadioGroup
                                    optionType="button"
                                    options={
                                      plansReq.data?.data?.map(plan => {
                                        return {
                                          label: `${plan.issueCount}${isZhCN ? "期" : " issues"}`,
                                          value: plan.id
                                        }
                                      })
                                    }
                                  />
                                </Form.Item>
                              )
                            } else if (timeType === "HISTORICAL") {
                              return (
                                <Form.Item
                                  label={<FormattedMessage id="mall.SubscriptionSelect"/>}
                                  help=""
                                  name={"periods"}
                                  hasFeedback={false}
                                  rules={[{required: false}]}
                                >
                                  <HxMallJournalPeriodPicker journalId={journalId!}/>
                                </Form.Item>
                              );
                            }
                            return null;
                          }}
                        </Form.Item>

                        <Form.Item label={null} style={{marginTop: 48}}>
                          <Button
                            className={'buy-submit-btn'}
                            loading={plansReq.loading || periodExistReq.loading}
                            type="primary"
                            htmlType="submit"
                            size={"large"}
                          >
                            <FormattedMessage id="mall.BuyNow"/>
                          </Button>
                        </Form.Item>
                      </Form>
                    )}
                    <div className={"mall-product-detail-info-meta-desc"}>
                      <FormattedMessage id="mall.SubscriptionStatsDesc" values={{
                        count: (journal?.subscribeNum || 0) > 100 ? journal?.subscribeNum : 100
                      }}/>
                      <br/>
                      <FormattedMessage id="mall.Hotline" values={{
                        desc: <span className={"meta-contact"}>{correspVal(isZhCN, siteInfo?.phone.textCn, siteInfo?.phone.textEn)}</span>
                      }}/>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className={"mall-product-detail-info-bottom"}>
              <HxCyCard title={"期刊详情"} size={"small"}>
                <>
                  <JournalInfoMeta className={"mall-product-journal-meta"} journal={journal}/>
                  <div className={"mall-product-journal-desc"}>
                    {correspVal(isZhCN, journal?.journalBreviaryIntroductionCn, journal?.journalBreviaryIntroductionEn)}
                  </div>
                </>
              </HxCyCard>

            </div>
          </div>
          <div className={"mall-product-detail-more"}>
            <div className={"mpdm-tip"}>
              <FormattedMessage id="mall.post-subscription.title"/>
              <ul className={"mpdm-tip-ul"}>
                <li><FormattedMessage id="mall.post-subscription.process1"/></li>
                <li><FormattedMessage id="mall.post-subscription.process2"/></li>
              </ul>
            </div>
            <div className={"mpdm-table-wrapper"}>
              <table className={"mpdm-table"}>
                <thead>
                <tr>
                  <th align={"left"}><FormattedMessage id="mall.post-subscription.journal-name"/></th>
                  <th align={"right"}><FormattedMessage id="mall.post-subscription.circulation-code"/></th>
                </tr>
                </thead>
                <tbody>
                {
                  postJournals.map(d => {
                    return (
                      <tr key={d.code}>
                        <td align={"left"}>{d.name}</td>
                        <td align={"right"}>{d.code}</td>
                      </tr>
                    )
                  })
                }
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <div className={"mall-product-detail-right"}>
          <div className={"mall-product-detail-right-content"}>
            <HealthScienceAd/>
            <MallJournalsGuess journalId={journalId}/>
          </div>
        </div>

        {
          !!orderConfirmInfo && (
            <KfModal
              title={null}
              open={true}
              destroyOnClose={true}
              onCancel={() => {
                setOrderConfirmInfo(undefined);
              }}
            >
              <MallOrderContext.Provider value={{
                onPaymentSuccess
              }}>
                <MallOrderConfirmInfo orderConfirmInfo={orderConfirmInfo} onCancel={() => setOrderConfirmInfo(undefined)}/>
              </MallOrderContext.Provider>
            </KfModal>
          )
        }
      </div>
    </div>
  );
};

export default MallProductDetail;
